<template>
  <view class="login-fanhui">
    <image src="../../static/icon/login-pop-up/fanhui.png" mode="widthFix" @click="fanHui"></image>
  </view>
  <view class="login-view">
    <text>登录一下，走远一点 </text>
    <text>慢慢理解世界，慢慢更新自己</text>
  </view>
  <view class="login-input">
    <view class="input-view">
      <input
        v-model="email"
        type="text"
        focus
        :cursor-spacing="15"
        placeholder="输入QQ邮箱"
        placeholder-class="input-style"
      />
    </view>
    <!-- 新增：邮箱类型提示 -->
    <view class="email-tip">仅支持QQ邮箱（@qq.com）</view>
    <view class="input-view" v-if="!codeShow">
      <input
        type="text"
        v-model="password"
        password
        :cursor-spacing="15"
        placeholder="输入密码"
        placeholder-class="input-style"
      />
    </view>
    <view v-if="codeShow" class="input-view global-display global-a-items">
      <input
        v-model="code"
        type="number"
        :cursor-spacing="15"
        placeholder="输入验证码"
        placeholder-class="input-style"
      />
      <button size="mini" hover-class="none" :disabled="codeDisabled" @click="sendCode">
        {{ codeName }}
      </button>
    </view>
    <button hover-class="none" class="go-button" @click="goLogin">登录</button>
    <view class="Login-switch global-display global-a-items global-j-content">
      <text @click="codeShow = !codeShow">{{ codeShow ? '账号登陆' : '验证码登陆' }}</text>
      <text @click="uploadPassword">忘记密码</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { codeLoginAPI, passwordLoginAPI, sendCodeAPI } from '@/api/login'
import { MenuButton } from '@/api/MenuButton'
// console.log(MenuButton().top);

// 邮箱。密码，验证码
const email = ref('')
const password = ref('')
const code = ref('')
// 验证码登陆和密码登录切换
const codeShow = ref(false)
/* ----------------登录逻辑----------------- */
const codeDisabled = ref(false)
const countdownTime = ref(60) //倒计时时间
const codeName = ref('发送验证码')

// 仅支持 QQ 邮箱校验
function validateQqEmail(value: string): boolean {
  const trimmed = value.trim()
  return /^[A-Za-z0-9._%+-]+@qq\.com$/.test(trimmed)
}

// 发送验证码
async function sendCode() {
  // 发送前校验 QQ 邮箱
  if (!validateQqEmail(email.value)) {
    wx.showToast({
      title: '仅支持QQ邮箱（@qq.com）',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  // 调用发送验证码接口
  try {
    codeDisabled.value = true
    const res = await sendCodeAPI(email.value)
    if (res.msg !== 'SUCCESS') {
      wx.showToast({
        title: res.msg,
        icon: 'none',
        duration: 2000,
      })
      return
    } else {
      wx.showToast({
        title: '验证码已发送',
        icon: 'none',
        duration: 2000,
      })
      // 倒计时开始
      var timer = setInterval(() => {
        if (countdownTime.value > 1) {
          countdownTime.value--
          codeName.value = `${countdownTime.value}秒后重新获取`
        } else {
          clearInterval(timer)
          codeDisabled.value = false
          countdownTime.value = 60
          codeName.value = '发送验证码'
        }
      }, 1000)
    }
  } catch (error) {}
}
// 验证码和密码登录
async function goLogin() {
  wx.showLoading({ title: '登陆中', mask: true })
  // 登录前校验 QQ 邮箱
  if (!validateQqEmail(email.value)) {
    wx.showToast({
      title: '仅支持QQ邮箱（@qq.com）',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  if (codeShow.value) {
    // 验证码登录时校验验证码
    if (!code.value) {
      wx.showToast({ title: '请输入验证码', icon: 'none', duration: 2000 })
      return
    }
    try {
      const res = await codeLoginAPI(email.value, code.value)
      console.log('验证码登录返回数据:', res)
      if (res.msg !== 'SUCCESS') {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        })
        return
      } else {
        wx.showToast({
          title: '登录成功',
          icon: 'none',
          duration: 2000,
        })
        // 确保存储完整的用户信息
        console.log('存储用户信息:', res)
        wx.setStorageSync('userInfor', res.data) //存
        
        // 检查存储是否成功
        const storedData = wx.getStorageSync('userInfor')
        console.log('验证存储的用户信息:', JSON.stringify(storedData))
        
        // 先发送登录成功事件
        uni.$emit('loginSuccess', true)
        // 延迟跳转，确保事件被正确处理
        setTimeout(() => {
          uni.switchTab({ url: '/pages/mine/mine' })
        }, 1000) // 增加延迟时间
      }
    } catch (error) {
      wx.showToast({
        title: '登录失败，请稍后再试',
        icon: 'none',
        duration: 2000,
      })
      return
    }
  } else {
    // 密码登录时校验密码
    if (!password.value) {
      wx.showToast({ title: '请输入密码', icon: 'none', duration: 2000 })
      return
    }
    try {
      const res = await passwordLoginAPI(email.value, password.value)
      console.log('密码登录返回数据:', JSON.stringify(res))
      if (res.msg !== 'SUCCESS') {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        })
        return
      } else {
        wx.showToast({
          title: '登录成功',
          icon: 'none',
          duration: 2000,
        })
        // 确保存储完整的用户信息
        console.log('存储用户信息:', JSON.stringify(res.data))
        wx.setStorageSync('userInfor', res.data) //存
        
        // 检查存储是否成功
        const storedData = wx.getStorageSync('userInfor')
        console.log('验证存储的用户信息:', JSON.stringify(storedData))
        
        // 先发送登录成功事件
        uni.$emit('loginSuccess', true)
        // 延迟跳转，确保事件被正确处理
        setTimeout(() => {
          uni.switchTab({ url: '/pages/mine/mine' })
        }, 1000) // 增加延迟时间
      }
    } catch (error) {
      wx.showToast({
        title: '登录失败，请稍后再试',
        icon: 'none',
        duration: 2000,
      })
      return
    }
  }
}
// 忘记密码
function uploadPassword() {
  wx.navigateTo({ url: '/pages/password-settings/password-settings' })
}
// 返回上一页
function fanHui() {
  uni.navigateBack({ delta: 1 })
}
</script>

<style>
page {
  background-image: url('https://lvyou-1332935562.cos.ap-nanjing.myqcloud.com/ceshi%2FIMG_0602.PNG');
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  /* min-height: 100vh; */
}
.login-fanhui {
  padding-top: v-bind('MenuButton().top');
  height: v-bind('MenuButton().height');
  display: flex;
  align-items: center;
}
.login-fanhui image {
  width: 40rpx;
  display: block;
  margin-left: 20rpx;
}
.login-view {
  padding-top: 160rpx;
  padding-bottom: 140rpx;
}
.login-view text {
  padding-left: 40rpx;
  color: #ffffff;
}
.login-view text:nth-child(1) {
  font-size: 50rpx;
  font-weight: bold;
  padding-bottom: 40rpx;
}
.login-view text:nth-child(2) {
  font-size: 38rpx;
  font-family: 'myfont';
}
.login-input {
  /* background-color: #ffffff; */
  margin: 0 40rpx;
  padding: 40rpx 30rpx;
  background: rgba(255, 255, 255, 0.12);
  border: 1rpx solid rgba(255, 255, 255, 0.25);
  border-radius: 32rpx;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.18);
  backdrop-filter: blur(8rpx);
}
.login-input button {
  background: linear-gradient(135deg, #ffe36a 0%, #f8d93a 100%);
  color: #333;
  border: none;
}
.input-style {
  color: #ffffff;
}
.input-view {
  background-color: rgba(255, 255, 255, 0.18);
  height: 100rpx;
  padding: 0 30rpx;
  border-radius: 40rpx;
  margin: 30rpx 0;
  color: #ffffff;
  font-size: 30rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}
.input-view input {
  height: 100rpx;
}
/* 验证码按钮（mini） */
.input-view button {
  margin-left: 20rpx;
  height: 64rpx;
  line-height: 64rpx;
  padding: 0 24rpx;
  border-radius: 32rpx;
}
/* 禁用态 */
button[disabled] {
  opacity: 0.7;
}
.go-button {
  width: 100%;
  border-radius: 44rpx;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 32rpx;
  font-weight: 600;
  letter-spacing: 2rpx;
  color: #3a2a00;
  background: linear-gradient(135deg, #ffe36a 0%, #ffc93a 50%, #ffb321 100%);
  border: 1rpx solid rgba(255, 255, 255, 0.35);
  box-shadow: 0 12rpx 28rpx rgba(255, 189, 46, 0.45), inset 0 -6rpx 12rpx rgba(0, 0, 0, 0.08),
    inset 0 6rpx 12rpx rgba(255, 255, 255, 0.35);
  text-shadow: 0 2rpx 2rpx rgba(255, 255, 255, 0.25);
  transition: transform 0.12s ease, box-shadow 0.12s ease, filter 0.12s ease;
}

.go-button::after {
  border: none;
}

.go-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 8rpx 18rpx rgba(255, 189, 46, 0.35), inset 0 -4rpx 10rpx rgba(0, 0, 0, 0.08),
    inset 0 4rpx 10rpx rgba(255, 255, 255, 0.3);
  filter: brightness(0.98);
}
.Login-switch {
  color: #ffffff;
  padding-top: 20rpx;
}
/* 新增：邮箱提示样式 */
.email-tip {
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
  margin-top: -10rpx;
  padding-left: 10rpx;
}
</style>
